package net.wanho.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import lombok.SneakyThrows;
import net.wanho.entity.Student;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * Author：汤小洋
 * Date：2023-08-29 11:22
 * Description：<描述>
 */
@RestController
public class EasyExcelController {

    @SneakyThrows
    @RequestMapping("/export2")
    public void export2(HttpServletResponse response){
        List<Student> list = new ArrayList<>();
        list.add(new Student(1, "张三", 18, 1, "北京", LocalDateTime.now()));
        list.add(new Student(2, "李四", 18, 0, "北京", LocalDateTime.now()));
        list.add(new Student(3, "王五", 18, 1, "北京", LocalDateTime.now()));

        // 设置响应内容类型
        response.setContentType("application/x-excel");
        // 设置处理方式为附件，并指定文件名
        response.setHeader("Content-Disposition", "attachment;filename="+ new String("学生信息表.xlsx".getBytes("utf-8"), "iso-8859-1"));

        EasyExcel.write(response.getOutputStream(), Student.class)
                .sheet("学生表")
                .doWrite(list);
    }

    @RequestMapping("/import2")
    public void import2(){
        EasyExcel.read("C:\\Users\\Administrator\\Downloads\\Document\\学生信息表.xlsx", Student.class, new ReadListener<Student>() {
                    List<Student> list = new ArrayList<>();

                    @Override
                    public void invoke(Student student, AnalysisContext analysisContext) {
                        list.add(student);
                    }

                    @Override
                    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
                        list.forEach(System.out::println);
                    }
                })
                .sheet("学生表")
                .doRead();
    }

}
